﻿using StriveEngine.Core;
using StriveEngine.Tcp.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;

namespace StriveEngine.SimpleDemoServer
{
    public class StriveEngineUtils
    {
        private ITcpServerEngine tcpServerEngine;
        private bool hasTcpServerEngineInitialized;
        private object obj = new object();
        private static StriveEngineUtils striveEngineUtils;
        private StriveEngineUtils()
        {
            lock (obj)
            {
                try
                {
                    if (this.tcpServerEngine == null)
                    {

                        this.tcpServerEngine = NetworkEngineFactory.CreateTextTcpServerEngine(9000, new DefaultTextContractHelper("\0"));//DefaultTextContractHelper是StriveEngine内置的ITextContractHelper实现。使用UTF-8对EndToken进行编码。 
                    }

                    if (this.hasTcpServerEngineInitialized)
                    {
                        this.tcpServerEngine.ChangeListenerState(true);
                    }
                    else
                    {
                        this.InitializeTcpServerEngine();
                    }

                    //this.ShowListenStatus();
                }
                catch (Exception ee)
                {
                    //MessageBox.Show(ee.Message);
                }
            }
        }

        public static StriveEngineUtils GetStriveEngineUtils()
        {
            if (striveEngineUtils == null)
            {
                striveEngineUtils = new StriveEngineUtils();
            }
            return striveEngineUtils;
        }

        private void InitializeTcpServerEngine()
        {
            //this.tcpServerEngine.ClientCountChanged += new CbDelegate<int>(tcpServerEngine_ClientCountChanged);
            this.tcpServerEngine.ClientConnected += new CbDelegate<System.Net.IPEndPoint>(tcpServerEngine_ClientConnected);
            this.tcpServerEngine.ClientDisconnected += new CbDelegate<System.Net.IPEndPoint>(tcpServerEngine_ClientDisconnected);
            this.tcpServerEngine.MessageReceived += new CbDelegate<IPEndPoint, byte[]>(tcpServerEngine_MessageReceived);
            this.tcpServerEngine.Initialize();
            this.hasTcpServerEngineInitialized = true;

        }
        System.Timers.Timer t;//定时器
        /// <summary>
        /// 一个新的设备上线
        /// </summary>
        /// <param name="ipe"></param>
        void tcpServerEngine_ClientConnected(System.Net.IPEndPoint ipe)
        {
            ////上线后 将其他人发送回去
            t = new System.Timers.Timer();
            t.Interval = 1000;
            t.Elapsed += tick;
            t.Start();

        }
        void tick(object o, EventArgs e)
        {
            t.Stop();
            //首先获取所有在线设备
            List<IPEndPoint> list = this.tcpServerEngine.GetClientList();
            string shebeiid = "";
            if (list != null)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    shebeiid += list[i].ToString() + ",";
                }
                string msg = "_10001:" + shebeiid;// "\0" 表示一个消息的结尾


                for (int i = 0; i < list.Count; i++)
                {
                    string result = msg;
                    if (this.tcpServerEngine.IsWebClient(list[i]) == null || !(bool)this.tcpServerEngine.IsWebClient(list[i]))
                    {
                        result += "\0";
                    }
                    byte[] bMsg = System.Text.Encoding.UTF8.GetBytes(result);//消息使用UTF-8编码
                    this.tcpServerEngine.SendMessageToClient(list[i], bMsg);
                }
            }
        }
        void tcpServerEngine_ClientDisconnected(System.Net.IPEndPoint ipe)
        {
            //上线后 将其他人发送回去
            t = new System.Timers.Timer();
            t.Interval = 1000;
            t.Elapsed += tick;
            t.Start();
        }
        void tcpServerEngine_MessageReceived(IPEndPoint client, byte[] bMsg)
        {
            string msg = System.Text.Encoding.UTF8.GetString(bMsg); //消息使用UTF-8编码
            msg = msg.Substring(0, msg.Length - 1); //将结束标记"\0"剔除
            
            //将消息转发
            List<IPEndPoint> list = this.tcpServerEngine.GetClientList();
            if (list != null)
            {
                IPEndPoint result = list.Find(t => msg.StartsWith(t.Port.ToString()));
                if (result != null)
                {
                    this.tcpServerEngine.SendMessageToClient(result, bMsg);
                }
            }
        }
    }
}